<?php
namespace App\Components;
use Log;
/**
 * 文件上传工具类
 * @author 郭钊林
 */
class FileTools{
  public $img_size = 2097152;   //2M
  public $video_size = 536870912;  //500M
  public $img_suffix = ['gif','jpg','jpeg','png','bmp'];
  public $video_suffix = ['mp3','mp4'];
  public $pdf_suffix = ['pdf'];
  public $cdn_root = '';
  
  public function __construct() {
	$this->document_root=env('FILE_DOMAIN') ? env('FILE_DOMAIN') : $_SERVER['DOCUMENT_ROOT'];
    $this->cdn_root = '/data/cdn_dy';
  }

  /**
   * 封装所有的单个文件上传方法
   * $path 文件路径
   * $ext 后缀名
   * $change_file_name 是否改变源文件名称
   * $dir_date 是否需要根据日期创建路径文件夹
   */
  public function uploadSim($path,$size,$ext,$change_file_name = true,$dir_date = true){
    $result = ['error' => false,'msg' => '','data' => ''];
    $path = $dir_date ? ($this->document_root.$path.'/'.date('Ym').'/'.date('d').'/') : ($this->document_root.$path);
    $this->createFolder($path);
    if(isset($_FILES)){
      if($_FILES['file']['error'] != 0){
        $result['error'] = true;
        $result['msg'] = '上传有误';
        return $result;
      }
      if($_FILES['file']['size'] > $size){
        $result['error'] = true;
        $result['msg'] = '上传文件太大';
        return $result;
      }
      if(isset($_FILES['file']['name']) && !empty($_FILES['file']['name'])){
        $name_arr = explode('.',$_FILES['file']['name']);
        $suffix = end($name_arr);
        if(!in_array(strtolower($suffix),$ext)){
          $result['error'] = true;
          $result['msg'] = '文件格式错误';
        }else{
          $file_name = $change_file_name ? (md5($_FILES['file']['tmp_name']).'.'.$suffix) : iconv("UTF-8","gb2312",$_FILES['file']['name']);
          $file_path = $path.$file_name;
		  echo $file_pathe;exit();
          if(!move_uploaded_file($_FILES['file']['tmp_name'],$file_path)){
            $result['error'] = true;
            $result['msg'] = '上传失败';
          }else{
            $result['data'] = $dir_date ? ('/'.date('Ym').'/'.date('d').'/'.$file_name) : ('/'.$file_name);
          }
        }
      }
    }
    return $result;
  }
    
  /**
   * 封装所有的多个文件上传方法
   * $path 文件路径
   * $ext 后缀名
   * $appoint_file_name 指定文件名称  不带后缀
   * $change_file_name 是否改变源文件名称 
   * $dir_date 是否需要根据日期创建路径文件夹
   */
  public function uploadMultiple($path,$size,$ext,$change_file_name = true,$dir_date = true){
    $result = ['error' => false,'msg' => '','data' => []];
    $path = $dir_date ? ($this->document_root.$path.'/'.date('Ym').'/'.date('d').'/') : ($this->document_root.$path);
    $this->createFolder($path);
    if(isset($_FILES)){
      $file_error = false;
      foreach ($_FILES['file']['error'] as $error){
        $error != 0 && $file_error = true;
      }
      if($file_error){
        $result['error'] = true;
        $result['msg'] = '上传失败';
      }else{
        $file_size = false;
        foreach ($_FILES['file']['size'] as $f_size){
          $f_size > $size && $file_size = true;
        }
        if($file_size){
          $result['error'] = true;
          $result['msg'] = '文件大小不能大于2M';
        }else{
          $file_type = false;
          if($ext){//需要判断文件后缀
            foreach ($_FILES['file']['name'] as $file_name){
              $name_arr = explode('.',$file_name);
              $suffix = end($name_arr);
              if(is_array($ext)){
                !in_array(strtolower($suffix),$ext) && $file_type = true;
              }else{
                (strtolower($suffix) != $ext) && $file_type = true;
              }
            }
          }
          if($file_type){
            $result['error'] = true;
            $result['msg'] = '格式错误';
          }else{
            $data = [];
            $file_tmp_name = false;
            foreach ($_FILES['file']['tmp_name'] as $key => $tmp_name){
              $s_file_name = explode('.',$_FILES['file']['name'][$key]);
              $s_ext = end($s_file_name);
              $file_name = $change_file_name ? (md5($tmp_name).'.'.$s_ext) : iconv("UTF-8","gb2312",$_FILES['file']['name'][$key]);
              $file_path = $path . '/' . $file_name;
              $file_paths['name'] = $s_file_name[0];
              $file_paths['size'] = $_FILES['file']['size'][$key];
              $file_paths['path'] = $dir_date ? ('/'.date('Ym').'/'.date('d').'/'.$file_name) : $file_name;
              if(!move_uploaded_file($tmp_name, $file_path)){
                $file_tmp_name = true;
              }
              $data[] = $file_paths;
            }
            if($file_tmp_name){
              $result['error'] = true;
              $result['msg'] = '上传失败';
              $result['data'] = [];
            }else{
              $result['data'] = $data;
            }
          }
        }
      }
    }else{
      $result['error'] = true;
      $result['msg'] = '请选择';
    }
    return $result;
  }
  
  /**
   * 封装所有的多个文件上传方法 -- 上传到xzb_file目录
   * $path 文件路径
   * $ext 后缀名
   * $appoint_file_name 指定文件名称  不带后缀
   * $change_file_name 是否改变源文件名称 
   * $dir_date 是否需要根据日期创建路径文件夹
   */
  public function pptUpload($path,$size,$ext,$change_file_name = true,$dir_date = true){
    $result = ['error' => false,'msg' => '','data' => []];
    $path = $dir_date ? ($this->document_root.$path.'/'.date('Ym').'/'.date('d').'/') : ($this->document_root.$path);
    $this->createFolder($path);
    if(isset($_FILES)){
      $file_error = false;
      foreach ($_FILES['file']['error'] as $error){
        $error != 0 && $file_error = true;
      }
      if($file_error){
        $result['error'] = true;
        $result['msg'] = '上传失败';
      }else{
        $file_size = false;
        foreach ($_FILES['file']['size'] as $f_size){
          $f_size > $size && $file_size = true;
        }
        if($file_size){
          $result['error'] = true;
          $result['msg'] = '文件大小不能大于2M';
        }else{
          $file_type = false;
          if($ext){//需要判断文件后缀
            foreach ($_FILES['file']['name'] as $file_name){
              $name_arr = explode('.',$file_name);
              $suffix = end($name_arr);
              if(is_array($ext)){
                !in_array(strtolower($suffix),$ext) && $file_type = true;
              }else{
                (strtolower($suffix) != $ext) && $file_type = true;
              }
            }
          }
          if($file_type){
            $result['error'] = true;
            $result['msg'] = '格式错误';
          }else{
            $data = [];
            $file_tmp_name = false;
            foreach ($_FILES['file']['tmp_name'] as $key => $tmp_name){
              $s_file_name = explode('.',$_FILES['file']['name'][$key]);
              $s_ext = end($s_file_name);
              $file_name = $change_file_name ? (md5($tmp_name).'.'.$s_ext) : iconv("UTF-8","gb2312",$_FILES['file']['name'][$key]);
              $file_path = $path . '/' . $file_name;
              if(!move_uploaded_file($tmp_name, $file_path)){
                $file_tmp_name = true;
              }
              $data[] = $dir_date ? ('/'.date('Ym').'/'.date('d').'/'.$file_name) : $file_name;
            }
            if($file_tmp_name){
              $result['error'] = true;
              $result['msg'] = '上传失败';
              $result['data'] = [];
            }else{
              $result['data'] = $data;
            }
          }
        }
      }
    }else{
      $result['error'] = true;
      $result['msg'] = '请选择';
    }
    return $result;
  }
  
  /**
  ** 创建文件夹
  ** path 文件路径
  **
  */
  private function createFolder($path) {
    if (!file_exists($path)) {
      $this->createFolder(dirname($path));
      mkdir($path);
      chmod($path, 0777);
    }
    return true;
  }
    
  /**
   * 读取文件夹列表
   * 单个文件夹，不读取文件夹下文件夹的内容
   */
  public function readFolderList($path){
    $file_arr = [];
    $path = $this->document_root.$path;
    if(is_dir($path)){
      foreach(scandir($path) as $key => $file){
        if($file == '.'|| $file == '..') continue;
        if(!is_dir($path.'/'.$file)){   //不是文件夹
          $data['id'] = $key - 1;
          $data['file_name'] = $file;
          $fCont = file_exists($path.'/'.$file) ? file_get_contents($path.'/'.$file) : '';
          $data['file_size'] = !empty($fCont) ? (Tools::showFileSize(strlen($fCont))) : 0;
          $file_arr[] = $data;
        }
      }
    }
    return $file_arr;
  }
    
  /**
   * $path 路径
   * 获取该路径下文件夹列表
   */
  public function getFolderList($path){
    $file_arr = [];
    $path = $this->document_root.$path;
    if(is_dir($path)){
      foreach(scandir($path) as $key => $file){
        if($file == '.'|| $file == '..') continue;
        if(is_dir($path.'/'.$file)){   //是文件夹
          $data['id'] = $key - 1;
          $data['file_name'] = $file;
          $file_arr[] = $data;
        }
      }
    }
    return $file_arr;
  }
    
  /**
   * 删除某一个文件 - xzb_file 目录里的
   * $path配置文件里的相对路径
   * $file_name文件名称
   */
  public function deleteFile($path,$file_name){
    $result = ['error' => false,'msg' => '','data' => ''];
    $file = $this->document_root.$path.'/'.$file_name;
    if(file_exists($file)){
      unlink($file);
      $result['msg'] = '删除成功';
      $result['data'] = TRUE;
    }else{
      $result['error'] = true;
      $result['msg'] = '文件不存在';
    }
    return $result;
  }

  /**
   * 删除某一个文件 - cdn_root 目录里的
   * $path配置文件里的相对路径
   * $file_name文件名称
   */
  public function newDeleteFile($file){
    $result = ['error' => false,'msg' => '','data' => ''];
    $file = $this->document_root.$file;
    if(file_exists($file)){
      unlink($file);
      $result['msg'] = '删除成功';
      $result['data'] = TRUE;
    }else{
      $result['error'] = true;
      $result['msg'] = '文件不存在';
    }
    return $result;
  }
    
  /**
  * 删除文件夹下面所有内容
  * 包括文件夹
  */
  public function deldir($path){
    $dir_path = $this->document_root.$path;
    $dh=opendir($dir_path);
    while($file=readdir($dh)) {
      if($file!='.' && $file!='..') {
        $fullpath=$dir_path.'/'.$file;
        if(!is_dir($fullpath)) {
          unlink($fullpath);
        }else{
          $this->deldir($path.'/'.$file);
        }
      }
    }
    closedir($dh);
    @rmdir($dir_path);
    return true;
  }
    
  /**
   * 创建文件夹
   */
  public function mkdirFload($path){
    $this->createFolder($this->document_root.$path);
  }

  /**
   * 读取文件内容
   */
  public function getContentFile($path){
    $path = $this->document_root.$path;
    $result = false;
    if(file_exists($path)){
      $result = file_get_contents($path);
    }
    return $result;
  }

  /**
   * 判断文件是否存在
   */
  public function fileIsRxist($path){
    $path = $this->document_root.$path;
    return file_exists($path) ? true : false;
  }
  
  /**
   * 传入文件url
   * 保存到服务器，返回保存地址
   */
  public function saveFile($path,$file_url = ''){
    $result = '';
    if(!empty($file_url)){
      $result = $path.'/'.date('Ym').'/'.date('d').'/';
      $path = $this->document_root.$path.'/'.date('Ym').'/'.date('d').'/';
      $this->createFolder($path);
      $file_ = file_get_contents($file_url);
      $image = getimagesize($file_url);
      $suffix = '.jpg'; 
      if(is_array($image) && isset($image['mime'])){
        $suffix = $this->getImageSuffix($image['mime']);
      }
      $file_name = md5($file_).$suffix;
      $path = $path.$file_name;
      if(!file_exists($path)){//如果图片不存在
        $file = fopen($path, "w"); //打开文件准备写入
        fwrite($file, $file_); //写入
        fclose($file);
      }
      $result = $result.$file_name;
    }
    return $result;
  }

  public function getImageSuffix($mime){
    $ext_arr = [
      'image/gif' => '.gif',
      'image/pjpeg' => '.jpg',
      'image/jpeg' => '.jpg',
      'image/png' => '.png',
      'image/x-png' => '.png'
    ];
    return isset($ext_arr[$mime]) ? $ext_arr[$mime] : '.jpg';
  }
  
  
  /**
   * 新单个文件上传方法
   * $path 文件路径
   * $ext 后缀名
   * $change_file_name 是否改变源文件名称
   * $dir_date 是否需要根据日期创建路径文件夹
   */
  public function newUpload($type,$size,$ext,$change_file_name = true,$dir_date = true){
    $result = ['error' => false,'msg' => '','data' => ''];
    $path = $dir_date ? ($this->cdn_root.$type.'/'.date('Ym').'/'.date('d').'/') : ($this->cdn_root.$type.'/');
    $this->mkdirFload($path);
	
    if(isset($_FILES)){
      if($_FILES['file']['error'] != 0){
        $result['error'] = true;
        $result['msg'] = '上传有误';
        return $result;
      }
      if($_FILES['file']['size'] > $size){
        $result['error'] = true;
        $result['msg'] = '上传文件太大';
        return $result;
      }
      if(isset($_FILES['file']['name']) && !empty($_FILES['file']['name'])){
        $name_arr = explode('.',$_FILES['file']['name']);
        $suffix = end($name_arr);
        if(!in_array(strtolower($suffix),$ext)){
          $result['error'] = true;
          $result['msg'] = '文件格式错误';
        }else{
          $file_name = $change_file_name ? (md5($_FILES['file']['tmp_name']).'.'.$suffix) : iconv("UTF-8","gb2312",$_FILES['file']['name']);
          $file_path = $this->document_root.$path.$file_name;
          if(!move_uploaded_file($_FILES['file']['tmp_name'],$file_path)){
            $result['error'] = true;
            $result['msg'] = '上传失败';
          }else{
            $result['data'] = $path ? ($path.$file_name) : '';
          }
        }
      }
    }
    return $result;
  }

  /**
   * 封装所有的多个文件上传方法 - 上传到cdn_root目录
   * $path 文件路径
   * $ext 后缀名
   * $appoint_file_name 指定文件名称  不带后缀
   * $change_file_name 是否改变源文件名称
   * $dir_date 是否需要根据日期创建路径文件夹
   */
  public function newMultiUpload($type,$size,$ext,$change_file_name = true,$dir_date = true){
    $result = ['error' => false,'msg' => '','data' => []];
    $path = $dir_date ? ($this->cdn_root.$type.'/'.date('Ym').'/'.date('d').'/') : $this->cdn_root.$type.'/';
    $this->createFolder($path);
    if(isset($_FILES)){
      $file_error = false;
      foreach ($_FILES['file']['error'] as $error){
        $error != 0 && $file_error = true;
      }
      if($file_error){
        $result['error'] = true;
        $result['msg'] = '上传失败';
      }else{
        $file_size = false;
        foreach ($_FILES['file']['size'] as $f_size){
          $f_size > $size && $file_size = true;
        }
        if($file_size){
          $result['error'] = true;
          $result['msg'] = '文件大小不能大于2M';
        }else{
          $file_type = false;
          if($ext){//需要判断文件后缀
            foreach ($_FILES['file']['name'] as $file_name){
              $name_arr = explode('.',$file_name);
              $suffix = end($name_arr);
              if(is_array($ext)){
                !in_array(strtolower($suffix),$ext) && $file_type = true;
              }else{
                (strtolower($suffix) != $ext) && $file_type = true;
              }
            }
          }
          if($file_type){
            $result['error'] = true;
            $result['msg'] = '格式错误';
          }else{
            $data = [];
            $file_tmp_name = false;
            foreach ($_FILES['file']['tmp_name'] as $key => $tmp_name){
              $s_file_name = explode('.',$_FILES['file']['name'][$key]);
              $s_ext = end($s_file_name);
              $origin_name = iconv("UTF-8","gb2312",str_replace('.'.$s_ext,'',$_FILES['file']['name'][$key]));
              //文件上传中文需要转编码
              $file_name = $change_file_name ? (md5($tmp_name).'.'.$s_ext) : ($origin_name.'.'.$s_ext);
              //返回给前端又不需要转编码
              $new_file_name = $change_file_name ? (md5($tmp_name).'.'.$s_ext) : (str_replace('.'.$s_ext,'',$_FILES['file']['name'][$key]).'.'.$s_ext);
              $file_path = $path.$file_name;
              if(!move_uploaded_file($tmp_name,$file_path)){
                $file_tmp_name = true;
              }
              $data[] = $dir_date ? ($type.'/'.date('Ym').'/'.date('d').'/'.$new_file_name) : ($type.'/'.$new_file_name);
            }
            if($file_tmp_name){
              $result['error'] = true;
              $result['msg'] = '上传失败';
              $result['data'] = [];
            }else{
              $result['data'] = $data;
            }
          }
        }
      }
    }else{
      $result['error'] = true;
      $result['msg'] = '请选择';
    }
    return $result;
  }
  
  public function canvasMultiUpload($type,$size,$ext,$change_file_name = true,$dir_date = true){
    $result = ['error' => false,'msg' => '','data' => []];
    $path = $dir_date ? ($this->cdn_root.$type.'/'.date('Ym').'/'.date('d').'/') : $this->cdn_root.$type.'/';
    $this->createFolder($path);
    if(isset($_FILES)){
      $file_error = false;
      foreach ($_FILES['file']['error'] as $error){
        $error != 0 && $file_error = true;
      }
      if($file_error){
        $result['error'] = true;
        $result['msg'] = '上传失败';
      }else{
        $file_size = false;
        foreach ($_FILES['file']['size'] as $f_size){
          $f_size > $size && $file_size = true;
        }
        if($file_size){
          $result['error'] = true;
          $result['msg'] = '文件大小不能大于2M';
        }else{
          $file_type = false;
          if($ext){//需要判断文件后缀
            foreach ($_FILES['file']['name'] as $file_name){
              $name_arr = explode('.',$file_name);
              $suffix = end($name_arr);
              if(is_array($ext)){
                !in_array(strtolower($suffix),$ext) && $file_type = true;
              }else{
                (strtolower($suffix) != $ext) && $file_type = true;
              }
            }
          }
          if($file_type){
            $result['error'] = true;
            $result['msg'] = '格式错误';
          }else{
            $data = [];
            $file_tmp_name = false;
            foreach ($_FILES['file']['tmp_name'] as $key => $tmp_name){
              $s_file_name = explode('.',$_FILES['file']['name'][$key]);
              $s_ext = end($s_file_name);
              $origin_name = iconv("UTF-8","gb2312",str_replace('.'.$s_ext,'',$_FILES['file']['name'][$key]));
              //文件上传中文需要转编码
              $file_name = $change_file_name ? (md5($tmp_name).'.'.$s_ext) : ($origin_name.'.'.$s_ext);
              //返回给前端又不需要转编码
              $new_file_name = $change_file_name ? (md5($tmp_name).'.'.$s_ext) : (str_replace('.'.$s_ext,'',$_FILES['file']['name'][$key]).'.'.$s_ext);
              $file_path = $path.$file_name;
              if(!move_uploaded_file($tmp_name,$file_path)){
                $file_tmp_name = true;
              }
              $url = $dir_date ? ($type.'/'.date('Ym').'/'.date('d').'/'.$new_file_name) : ($type.'/'.$new_file_name);
              $name = $_FILES['file']['name'][$key];
              $data[] = ['url'=>$url,'name'=>$name];
            }
            if($file_tmp_name){
              $result['error'] = true;
              $result['msg'] = '上传失败';
              $result['data'] = [];
            }else{
              $result['data'] = $data;
            }
          }
        }
      }
    }else{
      $result['error'] = true;
      $result['msg'] = '请选择';
    }
    Log::info("out result=".json_encode($result).", ". __FILE__.", ".__FUNCTION__.", ". __LINE__);
    return $result;
  }


  /**
   * 分销海报处理
   */
  public function pictureGD($share_img,$code_img,$data){
    $result = false;
    //1.创建画布，默认的背景是黑色
    $im = imagecreatetruecolor(750,1334);
    $pullpath = $this->cdn_root.$share_img;
    if(!file_exists($pullpath)){//如果图片不存在本地
      Log::info("分销海报处理错误：pullpath=".$pullpath);
    }else{
      $share_img = $this->cdn_root.$share_img;
      //加载源图片
      $share_img_info = getimagesize($share_img);
      $share_src_img = '';
      switch ($share_img_info['mime']){
        case 'image/jpeg':
          $share_src_img = imagecreatefromjpeg($share_img);
          break;
        case 'image/png':
          $share_src_img = imagecreatefrompng($share_img);
          break;
      }
      $share_img_width = $share_img_info[0];
      $share_img_height = $share_img_info[1];
      //拷贝源图片到目标画布
      imagecopy($im,$share_src_img,0,0,0,0,$share_img_width,$share_img_height);
      $code_img = $this->cdn_root.$code_img;
      $code_img = $this->abbreviation($code_img,$data['qrcode_width']*2,$data['qrcode_height']*2);
      //分销二维码
      //拷贝源图片到目标画布
      imagecopy($im,$code_img,($data['left']-700)*2,($data['top']-200)*2,0,0,$data['qrcode_width']*2,$data['qrcode_height']*2);
      $img_name = md5($code_img.time());
      $path = $this->cdn_root.$this->canvas.'/'.date('Ym').'/'.date('d').'/';
      $this->createFolder($path);
      $path = $path.$img_name.'.jpg';
      if(imagejpeg($im,$path)){
        $result = $this->canvas.'/'.date('Ym').'/'.date('d').'/'.$img_name.'.jpg';
      }
    }
    return $result;
  }
  
  /**
   * 缩略图
   */
  public function abbreviation($imgpath,$code_width,$code_height){
    $img_info = getimagesize($imgpath);
    $src_img = '';
    switch ($img_info['mime']){
      case 'image/jpeg':
        $src_img = imagecreatefromjpeg($imgpath);
        break;
      case 'image/png':
        $src_img = imagecreatefrompng($imgpath);
        break;
    }
    $fx = $img_info[0];
    $fy = $img_info[1];
    //缩放的长宽
    $sx = $code_width;
    $sy = $code_height;
    //4.生成目标图像资源
    $small = imagecreatetruecolor($sx,$sy);
    //5.进行缩放
    imagecopyresampled($small,$src_img,0,0,0,0,$sx,$sy,$fx,$fy);
    return $small;
  }
  
  /**
    * ckeditor编辑器图片上传
    */
  public function ckeditorUpload(){
    $result = ['uploaded'=>0,'error'=>['message'=>'']];
    if(isset($_FILES) && !empty($_FILES)){
      $filename = $_FILES['upload']['name'];
      $filesize = $_FILES['upload']['size'];
      if($filesize > $this->video_size){
        $result['error']['message'] = '文件大小不能超过500M';
      }else{
        $extension = pathInfo($filename,PATHINFO_EXTENSION);
        if(in_array($extension,['gif','jpg','jpeg','png','bmp','mp4'])){
          $path = $this->cdn_root.'/ckeditor/'.date('Ym').'/'.date('d').'/';
          $this->createFolder($path);
          $file_name = md5($_FILES['upload']['tmp_name']).'.'.$extension;
          move_uploaded_file($_FILES['upload']['tmp_name'],$path.$file_name);
          $uuid = str_replace('.','',uniqid("",TRUE)).".".$extension;
          $result['uploaded'] = 1;
          unset($result['error']);
          $result['fileName'] = $uuid;
          $result['url'] = env('FILE_DOMAIN').'/ckeditor/'.date('Ym').'/'.date('d').'/'.$file_name;
        }else{
          $result['error']['message'] = '文件格式不正确（必须为.jpeg/.jpg/.gif/.bmp/.png/.mp4文件）';
        }
      }
    }else{
      $result['error']['message'] = '请选择上传的文件';
    }
    return json_encode($result,JSON_UNESCAPED_UNICODE);
  }
}